<template>
  <div class="model-config-container">
    <div class="config-sidebar">
      <div class="sidebar-header">
        <h3>模型配置</h3>
        <el-button type="primary" size="small" @click="createNewConfig">
          <el-icon><Plus /></el-icon> 新建
        </el-button>
      </div>

      <div class="config-list" v-loading="loadingList">
        <div
          v-for="config in configs"
          :key="config.id"
          :class="['config-item', { active: currentConfig?.id === config.id }]"
          @click="selectConfig(config)"
        >
          <div class="config-item-header">
            <span class="config-name">{{ config.model }}</span>
            <el-tag v-if="config.is_disabled" type="info" size="small" effect="dark">已禁用</el-tag>
          </div>
          <div class="config-desc">{{ config.remark || '暂无备注' }}</div>
        </div>
      </div>
    </div>

    <div class="config-main">
      <template v-if="currentConfig">
        <div class="main-header">
          <h2>{{ isEditing ? '编辑模型' : '新建模型' }}</h2>
          <div class="actions">
            <el-button type="primary" @click="saveConfig">保存</el-button>
            <el-button
              v-if="currentConfig.id"
              type="danger"
              @click="deleteConfig"
            >
              删除
            </el-button>
          </div>
        </div>

        <el-form :model="formData" label-position="top" class="config-form">
          <el-form-item label="API Key" required>
            <el-input v-model="formData.api_key" type="password" show-password placeholder="sk-xxx" />
          </el-form-item>

          <el-form-item label="Base URL" required>
            <el-input v-model="formData.base_url" placeholder="https://api.example.com/v1" />
          </el-form-item>

          <el-form-item label="模型" required>
            <el-input v-model="formData.model" placeholder="gpt-4o / claude-3-5-sonnet-20241022" />
          </el-form-item>

          <el-form-item label="备注">
            <el-input v-model="formData.remark" placeholder="可选备注信息" />
          </el-form-item>

          <el-form-item label="状态">
            <el-switch v-model="formData.is_disabled" active-text="禁用" inactive-text="启用" />
          </el-form-item>
        </el-form>
      </template>
      <div v-else class="empty-state">
        <el-empty description="请选择或创建一个模型配置" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import modelApi from '@/services/modelConfig'

const loadingList = ref(false)
const configs = ref([])
const currentConfig = ref(null)
const isEditing = ref(false)

const formData = reactive({
  api_key: '',
  base_url: '',
  model: '',
  remark: '',
  is_disabled: false
})

const loadData = async () => {
  loadingList.value = true
  try {
    const res = await modelApi.getConfigs()
    configs.value = res.data

    if (currentConfig.value?.id) {
      const updated = configs.value.find(c => c.id === currentConfig.value.id)
      if (updated) {
        selectConfig(updated)
      }
    }
  } catch (error) {
    ElMessage.error('加载数据失败: ' + error.message)
  } finally {
    loadingList.value = false
  }
}

const selectConfig = (config) => {
  currentConfig.value = config
  isEditing.value = true
  Object.assign(formData, {
    api_key: config.api_key,
    base_url: config.base_url,
    model: config.model,
    remark: config.remark,
    is_disabled: config.is_disabled
  })
}

const createNewConfig = () => {
  currentConfig.value = { id: null }
  isEditing.value = false
  Object.assign(formData, {
    api_key: '',
    base_url: '',
    model: '',
    remark: '',
    is_disabled: false
  })
}

const saveConfig = async () => {
  if (!formData.api_key || !formData.base_url || !formData.model) {
    ElMessage.warning('请填写所有必填字段')
    return
  }

  try {
    if (isEditing.value && currentConfig.value.id) {
      await modelApi.updateConfig(currentConfig.value.id, formData)
      ElMessage.success('更新成功')
    } else {
      const res = await modelApi.createConfig(formData)
      currentConfig.value = res.data
      isEditing.value = true
      ElMessage.success('创建成功')
    }
    loadData()
  } catch (error) {
    ElMessage.error('保存失败: ' + (error.response?.data?.detail || error.message))
  }
}

const deleteConfig = () => {
  ElMessageBox.confirm('确定要删除这个模型配置吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await modelApi.deleteConfig(currentConfig.value.id)
      ElMessage.success('删除成功')
      currentConfig.value = null
      loadData()
    } catch (error) {
      ElMessage.error('删除失败: ' + (error.response?.data?.detail || error.message))
    }
  })
}


onMounted(() => {
  loadData()
})
</script>

<style scoped>
.model-config-container {
  display: flex;
  height: 100%;
  background: var(--el-bg-color-page);
}

.config-sidebar {
  width: 300px;
  background: var(--el-bg-color);
  border-right: 1px solid var(--el-border-color);
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.config-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.config-item {
  padding: 12px;
  border-radius: 6px;
  cursor: pointer;
  margin-bottom: 8px;
  transition: all 0.2s;
  border: 1px solid var(--el-border-color-lighter);
  background: var(--el-bg-color);
}

.config-item:hover {
  background: var(--el-fill-color-light);
  border-color: var(--el-border-color);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.config-item.active {
  background: var(--el-color-primary-light-9);
  border-color: var(--el-color-primary);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.config-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.config-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.config-desc {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.config-main {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background: var(--el-bg-color);
  margin: 16px;
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);
}

.main-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--el-border-color);
}

.main-header h2 {
  margin: 0;
  font-size: 20px;
  color: var(--el-text-color-primary);
}

.config-form {
  max-width: 800px;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
</style>
